//
//  WHInfoAuthController.m
//  SquirrelCourier
//
//  Created by 邓伟浩 on 2019/1/4.
//  Copyright © 2019 邓伟浩. All rights reserved.
//

#import "WHInfoAuthController.h"
#import "WHAuthModel.h"
#import "WHAuthInfoCell.h"
#import "WHPhotoSelectTool.h"

typedef NS_ENUM(NSUInteger, AuthEditStatus) {
    AuthEditStatusUnEdit, // 未编辑
    AuthEditStatusNoUserName, // 未填写真实姓名
    AuthEditStatusNoIDCard, // 未填写身份证号
    AuthEditStatusIDCardError, // 无效的身份证号码
    AuthEditStatusNoPhoneNumber, // 未填写手机号码
    AuthEditStatusNoCity, // 未填写所属城市
    AuthEditStatusNoExpress, // 未填写所属城市
    
    AuthEditStatusNoFrontCard, // 未选择身份证正面
    AuthEditStatusNoReverseCard, // 未选择身份证背面
    AuthEditStatusDone, // 信息填写完成
};

@interface WHInfoAuthController ()<UITableViewDelegate, UITableViewDataSource, UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (nonatomic, strong) UITableView *infoTableView;
@property (nonatomic, strong) NSArray *tipsNameArray;
@property (nonatomic, strong) NSArray *placeHolderArray;
@property (nonatomic, strong) NSArray *infoKeyArray;
@property (nonatomic, strong) NSString *imageKey;
@property (nonatomic, strong) WHAuthModel *authModel;

@property (nonatomic, strong) UIButton *currentSelectButton;
@property (nonatomic, strong) NSURLSessionDataTask *authTask;

@end

@implementation WHInfoAuthController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"身份认证";
    
    [self initParams];
    [self setUpInfoTableView];
}

- (void)initParams {
    _authModel = [[WHAuthModel alloc] init];
    _tipsNameArray = @[@"真实姓名", @"身份证号", @"手机号码", @"所属城市", @"所属快递"];
    _placeHolderArray = @[@"请输入真实姓名", @"请输入身份证号", @"请输入有效手机号", @"请输入城市", @"请输入快递公司"];
    _infoKeyArray = @[@"cardName", @"cardNum", @"mobile", @"address", @"expressCompany"];
}

- (void)setUpInfoTableView {
    UITableView *infoTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view addSubview:infoTableView];
    infoTableView.delegate = self;
    infoTableView.dataSource = self;
    infoTableView.tableFooterView = [self tableFooterView];
    infoTableView.backgroundColor = CViewBgMainColor;
    infoTableView.separatorColor = CLineColor;
    infoTableView.separatorInset = UIEdgeInsetsMake(0, KNormalSpace, 0, -KNormalSpace);
    
    [infoTableView registerClass:[WHAuthInfoCell class] forCellReuseIdentifier:NSStringFromClass([WHAuthInfoCell class])];
    
    [infoTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view).offset(kTopHeight);
    }];
    
    _infoTableView = infoTableView;
}

- (UIView *)tableFooterView {
    UIView *tableFooterView = [[UIView alloc] init];
    tableFooterView.frame = CGRectMake(0, 0, KScreenWidth, kRealwidth(250));
    
    UIView *upLoadCardPhotoBack = [[UIView alloc] init];
    [tableFooterView addSubview:upLoadCardPhotoBack];
    upLoadCardPhotoBack.backgroundColor = KWhiteColor;
    upLoadCardPhotoBack.frame = CGRectMake(0, kRealwidth(10), KScreenWidth, kRealwidth(160));
    
    UILabel *tipsLabel = [[UILabel alloc] init];
    tipsLabel.textColor = CFontTitleBlackColor;
    tipsLabel.font = SYSTEMFONT(kRealwidth(16));
    tipsLabel.text = @"请上传身份证件照";
    [upLoadCardPhotoBack addSubview:tipsLabel];
    [tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(upLoadCardPhotoBack.mas_left).offset(kRealwidth(15));
        make.top.mas_equalTo(upLoadCardPhotoBack.mas_top).offset(kRealwidth(20));
        make.height.mas_equalTo(kRealwidth(16));
    }];
    
    UIButton *frontButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [frontButton setBackgroundImage:IMAGE_NAMED(@"button_selectImage_icon") forState:UIControlStateNormal];
    frontButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
    [upLoadCardPhotoBack addSubview:frontButton];
    [frontButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(upLoadCardPhotoBack.mas_left).offset(kRealwidth(25));
        make.width.height.mas_equalTo(kRealwidth(56));
        make.top.mas_equalTo(tipsLabel.mas_bottom).offset(kRealwidth(18));
    }];
    
    UILabel *leftTipsLabel = [[UILabel alloc] init];
    leftTipsLabel.textAlignment = NSTextAlignmentCenter;
    leftTipsLabel.font = SYSTEMFONT(kRealwidth(15));
    leftTipsLabel.textColor = CFontContentLightGrayColor;
    leftTipsLabel.text = @"身份证正面";
    [upLoadCardPhotoBack addSubview:leftTipsLabel];
    [leftTipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(frontButton.mas_bottom).offset(kRealwidth(15));
        make.height.mas_equalTo(kRealwidth(15));
        make.centerX.mas_equalTo(frontButton.mas_centerX);
    }];
    
    UIButton *reverseButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [reverseButton setBackgroundImage:IMAGE_NAMED(@"button_selectImage_icon") forState:UIControlStateNormal];
    reverseButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
    [upLoadCardPhotoBack addSubview:reverseButton];
    [reverseButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(frontButton.mas_right).offset(kRealwidth(59));
        make.width.height.mas_equalTo(kRealwidth(56));
        make.top.mas_equalTo(tipsLabel.mas_bottom).offset(kRealwidth(18));
    }];
    
    UILabel *middleTipsLabel = [[UILabel alloc] init];
    middleTipsLabel.textAlignment = NSTextAlignmentCenter;
    middleTipsLabel.font = SYSTEMFONT(kRealwidth(15));
    middleTipsLabel.textColor = CFontContentLightGrayColor;
    middleTipsLabel.text = @"身份证背面";
    [upLoadCardPhotoBack addSubview:middleTipsLabel];
    [middleTipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(reverseButton.mas_bottom).offset(kRealwidth(15));
        make.height.mas_equalTo(kRealwidth(15));
        make.centerX.mas_equalTo(reverseButton.mas_centerX);
    }];
    
    CGFloat leftGap = kRealwidth(32);
    UIButton *okButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [tableFooterView addSubview:okButton];
    NSString *okTitle = @"提交";
    NSAttributedString *okAttributeStr = [[NSAttributedString alloc] initWithString:okTitle attributes:@{NSFontAttributeName:SYSTEMFONT(kRealwidth(17)), NSForegroundColorAttributeName:KWhiteColor}];
    [okButton setAttributedTitle:okAttributeStr forState:UIControlStateNormal];
    [okButton setBackgroundImage:[UIImage imageWithColor:CMDarkOrangeColor] forState:UIControlStateNormal];
    okButton.frame = CGRectMake(leftGap, upLoadCardPhotoBack.bottom+kRealwidth(20), KScreenWidth-2*leftGap, kRealwidth(45));
    ViewRadius(okButton, kRealwidth(45)/2);
    [okButton addTarget:self action:@selector(okButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    [frontButton addTarget:self action:@selector(selectFrontPhoto:) forControlEvents:UIControlEventTouchUpInside];
    [reverseButton addTarget:self action:@selector(selectReversePhoto:) forControlEvents:UIControlEventTouchUpInside];
    
    return tableFooterView;
}

- (void)selectFrontPhoto:(UIButton *)button {
    _imageKey = @"cardFront";
    _currentSelectButton = button;
    [WHPhotoSelectTool showImagePickedAtViewController:self];
}

- (void)selectReversePhoto:(UIButton *)button {
    _imageKey = @"cardBack";
    _currentSelectButton = button;
    [WHPhotoSelectTool showImagePickedAtViewController:self];
}

#pragma mark - —————— UITableViewDelegate & UITableViewDataSource ——————

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _tipsNameArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WHAuthInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WHAuthInfoCell class]) forIndexPath:indexPath];
    cell.tipsLabel.text = _tipsNameArray[indexPath.row];
    [cell setInputTextPlaceHolder:_placeHolderArray[indexPath.row]];
    cell.messageField.text = [_authModel valueForKey:_infoKeyArray[indexPath.row]];
    
    if (indexPath.row == 0) {
        cell.validType = ValideTypeUserName;
    } else if (indexPath.row == 1) {
        cell.validType = ValideTypeIDCard;
    } else if (indexPath.row == 2) {
        cell.validType = ValideTypePhoneNumber;
    } else {
        cell.validType = ValideTypeUnkonw;
    }
    
    kWeakSelf(self);
    cell.textChangeBlock = ^(NSString *text) {
        [weakself.authModel setValue:text forKey:weakself.infoKeyArray[indexPath.row]];
    };
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kRealwidth(55);
}

#pragma mark - —————— UIImagePickerControllerDelegate ——————

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    [picker dismissViewControllerAnimated:YES completion:^{
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        [self.currentSelectButton setImage:image forState:UIControlStateNormal];
        [_authModel setValue:image forKey:_imageKey];
    }];
}

#pragma mark - —————— 事件 ——————
- (AuthEditStatus)checkAuthInfoIsCompletion {
    NSString *userName = self.authModel.cardName; // 真实姓名
    if (!ValidStr(userName)) return AuthEditStatusNoUserName;
    
    NSString *idNumber = self.authModel.cardNum; // 身份证号
    if (!ValidStr(idNumber)) return AuthEditStatusNoIDCard;
    
    if (![WHValidationHelper checkIdentityCardNo:idNumber]) return AuthEditStatusIDCardError;
    
    NSString *phoneNumber = self.authModel.mobile; // 手机号码
    if (!ValidStr(phoneNumber)) return AuthEditStatusNoPhoneNumber;
    
    NSString *city = self.authModel.address; // 所属城市
    if (!ValidStr(city)) return AuthEditStatusNoCity;
    
    NSString *express = self.authModel.expressCompany; // 所属快递
    if (!ValidStr(express)) return AuthEditStatusNoExpress;
    
    UIImage *frontImage = self.authModel.cardFront; // 身份证正面
    if (frontImage == nil) return AuthEditStatusNoFrontCard;
    
    UIImage *reverseImage = self.authModel.cardBack; // 身份证反面
    if (reverseImage == nil) return AuthEditStatusNoReverseCard;
    
    return AuthEditStatusDone;
}

- (void)okButtonClicked:(UIButton *)button {
    [self.view endEditing:YES];
    
    AuthEditStatus status = [self checkAuthInfoIsCompletion];
    NSString *errorStr;
    switch (status) {
        case AuthEditStatusNoUserName:
            errorStr = @"请填写真实姓名";
            break;
        case AuthEditStatusNoIDCard:
            errorStr = @"请填写身份证号";
            break;
        case AuthEditStatusIDCardError:
            errorStr = @"请填写正确的身份证号";
            break;
        case AuthEditStatusNoPhoneNumber:
            errorStr = @"请填写手机号码";
            break;
        case AuthEditStatusNoCity:
            errorStr = @"请填写所属城市";
            break;
        case AuthEditStatusNoExpress:
            errorStr = @"请填写所属快递";
            break;
        case AuthEditStatusNoFrontCard:
            errorStr = @"请选择身份证正面照片";
            break;
        case AuthEditStatusNoReverseCard:
            errorStr = @"请选择身份证反面照片";
            break;
        default:
            break;
    }
    if (errorStr) {
        [WHView showHudMsg:errorStr];
        
#if DEBUG
        [WHView showAlertwithTitle:nil message:NSStringFormat(@"useId: %d", userManager.detailUserInfo.userId)];
#endif
        
        return;
    }
    [self postAutonInfo];
}

- (void)postAutonInfo {
    NSString *postURL = NSStringFormat(@"%@%@", URL_main, URL_userAudit);
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @(userManager.detailUserInfo.userId), @"userId",
                          self.authModel.cardName, @"cardName",
                          self.authModel.cardNum, @"cardNum",
                          self.authModel.mobile, @"mobile",
                          self.authModel.address, @"address",
                          self.authModel.expressCompany, @"expressCompany",
                          nil];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *imageName = [formatter stringFromDate:[NSDate date]];
    
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    manger.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    NSArray *nameArray = @[@"cardFront", @"cardBack"];
    [MBProgressHUD showHudInView:nil];
    _authTask = [manger POST:postURL parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (int i = 0; i < nameArray.count; i++) {
            UIImage *image = [self.authModel valueForKey:nameArray[i]];
            NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
            DLog(@"upload image size: %ld k", (long)(imageData.length / 1024));
            NSString *fileName = NSStringFormat(@"%@-%d.png", imageName, i);
            [formData appendPartWithFileData:imageData name:nameArray[i] fileName:fileName mimeType:@"image/png"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        DLog(@"上传进度--->%f",uploadProgress.fractionCompleted);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:nil];
        DLog(@"responseObject: %@", responseObject);
        
        NSNumber *errcode = responseObject[@"errcode"];
        NSString *errmsg = responseObject[@"errmsg"];
        if (errcode.intValue == 0) {
            [WHView showAlertwithTitle:nil message:@"身份认证成功!" okAction:nil cancelAction:nil];
            
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [WHView showHudMsg:errmsg];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [WHView showMessage:@"上传失败" inView:self.view];
        [MBProgressHUD hideHUDForView:nil];
    }];
    
}

- (void)backBtnClicked {
    if (_authTask) {
        [_authTask cancel];
        _authTask = nil;
    }
    [super backBtnClicked];
}

@end
